package com.jy.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class DBUtil {
    private static final Logger log = LoggerFactory.getLogger(DBUtil.class);
    private static String driver = "";
    private static String url = "";
    private static String userName = "";
    private static String password = "";

    static {
        Properties properties = new Properties();
        try {
            //读取配置文件
            properties.load(new FileReader(DBUtil.class.getClassLoader().getResource("config.properties").getPath()));
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            userName = properties.getProperty("user");
            password = properties.getProperty("password");
            //加载数据库驱动
            Class.forName(driver);
        } catch (IOException e) {
            log.error(e.getMessage());
        } catch (ClassNotFoundException e) {
            log.error(e.getMessage());
        }
    }

    public static Connection getConnection(){
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, userName, password);
        } catch (SQLException throwables) {
            log.error(throwables.getMessage());
        }
        return conn;
    }

    public static void closeAll(Connection conn, Statement st, ResultSet rs){
        try{
            if (rs != null){
                rs.close();
            }
            if (st != null){
                st.close();
            }
            if (conn != null){
                conn.close();
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

    public static void main(String[] args) {
        log.info(getConnection().toString());
    }
}
